package net.xdclass.component;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.SmsConfig;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 功能描述
 *
 * @author ASUS
 * @date 2024/07/04  21:17
 */
@Component
@Slf4j
public class SmsComponent {
    private static final String URL_TEMPLATE ="https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    private static final String URL_TEMPLATE_NEW ="https://smssend.shumaidata.com/sms/send?templateId=%s&receive=%s&tag=%s";

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送短信验证码
     */
    @Async("threadPoolTaskExecutor")
    public void send(String to,String templateId,String value){
        long beginTime = CommonUtil.getCurrentTimestamp();

        String url = String.format(URL_TEMPLATE_NEW, templateId,to, value);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization","APPCODE "+smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        long endTime = CommonUtil.getCurrentTimestamp();
        //埋点http请求得出请求响应耗时【粗略统计，⾮线上⼤ᰁ数据测试得出】
        log.info("耗时：{},url:{},body:{}",endTime-beginTime,url,response.getBody());
        if(response.getStatusCode().is2xxSuccessful()){
            log.info("短信发送成功");
        }else{
            log.error("发送短信验证失败：{}",response.getBody());
        }

    }
}
